//
//  Exporter.m
//  BookMaker
//
//  Created by Mathieu Tozer on 22/11/07.
//  Copyright 2007 plasq. All rights reserved.
//

#import "Exporter.h"
#import "Book.h"
#import "Image.h"
#import "Page.h"
#import "CoreData+Additions.h"
#import <Quartz/Quartz.h>
@implementation Exporter

- (id) initWithBook:(Book *)book
{
	self = [super init];
	if (self != nil) {
		_book = book;
	}
	return self;
}

+ (Exporter *)exporterToExportBook:(Book *)book
{
	return [[Exporter alloc] initWithBook:book];
}

- (NSArray *)orderObjects:(NSArray *)unorderedObjects
{
	NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"order" ascending:YES];
	return [unorderedObjects sortedArrayUsingDescriptors:[NSArray arrayWithObject:sd]];
}

- (NSString *)pageNameWithFile:(NSString *)path pageOrder:(int )order
{
	return [NSString stringWithFormat:@"%@-%d.jpg", [path stringByExpandingTildeInPath], order];
}


- (NSArray *)orderObjectsWithPagesLeftToRight:(NSArray *)pages
{
	NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"xPosition" ascending:YES];	
	return [pages sortedArrayUsingDescriptors:[NSArray arrayWithObject:sd]];
}

- (void)exportPDFToPath:(NSString *)path
{
	//we're going to do this in two passes
	// 1, crop all the images and dump them in a folder at path
	
	NSArray *images = [self orderObjects:[[_book mutableSetValueForKey:@"images"] allObjects]];
	for (Image *image in images) {
		NSImage *fullImage = [[NSImage alloc] initWithContentsOfFile:[[image path] stringByExpandingTildeInPath]];
		NSArray *pages = [self orderObjectsWithPagesLeftToRight:[image pagesArray]]; //todo support other configs
		int order = 0;
		for (Page *page in pages) {
			NSRect pageRect = [page pageRect];
			NSImage *newCroppedPage =  [fullImage imageFromRect:pageRect];
			//write it out to path
			NSBitmapImageRep* bm = [NSBitmapImageRep imageRepWithData:[newCroppedPage TIFFRepresentation]];
			NSData *pageData = [bm representationUsingType:NSJPEGFileType properties:nil];
			NSLog(@"writing file %@ - %d", [image path], order);
			[pageData writeToFile:[self pageNameWithFile:[path stringByAppendingPathComponent:[[image path] lastPathComponent]] pageOrder:order] options:NSAtomicWrite error:nil];
			order++;
			[bm release];
		}
	}
	
	
	//now take up the task of making a pdf, and deleting all the images
	PDFDocument *doc = [[PDFDocument alloc] init];
	NSFileManager *fm = [NSFileManager defaultManager];
	NSArray *croppedFiles = [fm contentsOfDirectoryAtPath:path error:nil];
	if (croppedFiles) { // we really should have them, of course
		int pageCount = 0;
		for (NSString *file in croppedFiles) {
			//a page for each file
			PDFPage *newPage = [[PDFPage alloc] initWithImage:[[NSImage alloc] initWithContentsOfFile:[path stringByAppendingPathComponent:file]]];
			NSLog(@"processing pdf page file %@ - %d", file, pageCount);
			[doc insertPage:newPage atIndex:pageCount];
			pageCount++;
		}
	}
	[doc writeToFile:[path stringByAppendingPathComponent:@"The Book.pdf"]];
}

- (void)export:(NSString *)type toPath:(NSString *)path
{
	if ([type isEqualToString:@"pdf"]) {
		 [self exportPDFToPath:path];
	}
}

@end

